#include <libudev.h>
#include <string.h>
#include <iostream>
#include <string>
#include <fcntl.h>
#include <unistd.h>


// 读取 HDMI 状态
bool read_hdmi_state(const char *path) 
{
    int fd = open(path, O_RDONLY);
    if (fd == -1) {
        std::cerr << "Failed to open HDMI state file." << std::endl;
        return false;
    }

    char buffer[256] = {0};
    ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);
    close(fd);

    if (bytesRead <= 0) {
        std::cerr << "Failed to read HDMI state." << std::endl;
        return false;
    }

    return strstr(buffer, "VIDEO-IN=1") != nullptr;
}
void wait_for_display() 
{
    const char* display = getenv("DISPLAY");
    if (!display) {
        std::cerr << "DISPLAY environment variable not set." << std::endl;
        return;
    }

    std::cout << "Waiting for X server at " << display << "..." << std::endl;

    while (true) {
        // 使用 xdpyinfo 检查显示服务器是否响应
        int ret = system("xdpyinfo > /dev/null 2>&1");

        if (WIFEXITED(ret) && WEXITSTATUS(ret) == 0) {
            std::cout << "X server is ready." << std::endl;
            break;
        }

        sleep(1); // 每秒检查一次
    }
}
int main() 
{
    wait_for_display();
    char *hdmi_stata_path = "/sys/class/extcon/extcon7/state";
    if (read_hdmi_state(hdmi_stata_path)) {
        std::cout << "[HDMI 插入（开机状态）]" << std::endl;
        system("hdmi_insert.sh");
    } else {
        std::cout << "[HDMI 未插入（开机状态）]" << std::endl;
    }



    // 创建 udev 上下文
    struct udev *udev = udev_new();
    if (!udev) {
        std::cerr << "Failed to create udev context." << std::endl;
        return -1;
    }

    // 创建 udev monitor 对象，监听内核事件
    struct udev_monitor *mon = udev_monitor_new_from_netlink(udev, "kernel");
    if (!mon) {
        std::cerr << "Failed to create udev monitor." << std::endl;
        udev_unref(udev);
        return -1;
    }

    // 过滤只关注 extcon 子系统（用于 HDMI 热插拔）
    udev_monitor_filter_add_match_subsystem_devtype(mon, "extcon", NULL);
    udev_monitor_enable_receiving(mon);

    int fd = udev_monitor_get_fd(mon);
    std::cout << "Listening for udev events..." << std::endl;
    
    
    while (true) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        // 阻塞等待事件
        int ret = select(fd + 1, &fds, NULL, NULL, NULL);
        if (ret <= 0) continue;

        // 接收设备事件
        struct udev_device *dev = udev_monitor_receive_device(mon);
        if (dev) {
            const char *action = udev_device_get_action(dev);         // "change"
            const char *subsystem = udev_device_get_subsystem(dev);   // "extcon"
            const char *devpath = udev_device_get_devpath(dev);       // "/devices/platform/fdee0000.hdmirx-controller/extcon/extcon7"
            const char *name = udev_device_get_property_value(dev, "NAME");     // "fdee0000.hdmirx-controller"
            const char *state = udev_device_get_property_value(dev, "STATE");   // "VIDEO-IN=1" or "VIDEO-IN=0"

            // 判断是否是我们关心的设备
            if (name && strcmp(name, "fdee0000.hdmirx-controller") == 0) {
                if (state) {
                    std::cout << "HDMI Device State: " << state << std::endl;
                    if (strstr(state, "VIDEO-IN=1")) {
                        std::cout << "[HDMI 插入]" << std::endl;
                        int ret_ = system("hdmi_insert.sh");
                        if (ret_  == 0) {
                            std::cout << "===============hdmi_insert.sh 执行成功===============" << std::endl;
                        } else {
                            std::cerr << "===============hdmi_insert.sh 执行失败或异常退出===============" << std::endl;
                        }
                        // 在这里添加你想执行的操作，比如启动视频采集程序
                    } else if (strstr(state, "VIDEO-IN=0")) {
                        std::cout << "[HDMI 拔出]" << std::endl;
                        int ret_ = system("hdmi_remove.sh");
                        if (ret_  == 0) {
                            std::cout << ">>>>>>>>>>>>>>hdmi_remove.sh 执行成功<<<<<<<<<<<<<<<<" << std::endl;
                        } else {
                            std::cerr << ">>>>>>>>>>>>>>hdmi_remove.sh 执行失败或异常退出<<<<<<<<<<<<<<<<" << std::endl;
                        }
                        // 在这里添加你想执行的操作，比如停止视频采集程序
                    }
                }
            }

            udev_device_unref(dev);
        }
    }

    // 清理资源
    udev_monitor_unref(mon);
    udev_unref(udev);

    return 0;
}